package yiran.depositcumulative;

import org.bukkit.Bukkit;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.ServicesManager;
import org.bukkit.plugin.java.JavaPlugin;
import yiran.depositcumulative.api.DepositCumulativeAPI;
import yiran.depositcumulative.command.CumulativeCommand;
import yiran.depositcumulative.command.CumulativeTabCompleter;
import yiran.depositcumulative.data.DatabaseService;
import yiran.depositcumulative.lang.LangHelper;
import yiran.depositcumulative.lister.GUIListener;
import yiran.depositcumulative.lister.PointsListener;
import yiran.depositcumulative.output.Logger;

import java.io.File;

public final class DepositCumulative extends JavaPlugin {
    private GUIListener guiListener;
    @Override
    public void onEnable() {
        // 初始化日志系统
        Logger.init(this);

        // 确保配置文件存在
        File configFile = new File(getDataFolder(), "config.yml");
        if (!configFile.exists()) {
            saveResource("config.yml", false);
            Logger.info("已创建默认配置文件");
        }

        // 检查前置插件
        if (getServer().getPluginManager().getPlugin("PlayerPoints") == null) {
            Logger.error("PlayerPoints 未安装，插件将禁用");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }

        // 初始化语言系统
        LangHelper.init(this);

        // 初始化数据库
        DatabaseService databaseService = new DatabaseService(this);
        databaseService.connect();

        // 注册 PlaceholderAPI
        if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
            new DepositPlaceholder(this, databaseService).register();
            Logger.info("已挂钩 PlaceholderAPI");
        }

        // 注册命令
        getCommand("depositcumulative").setExecutor(new CumulativeCommand(databaseService, this));
        getCommand("depositcumulative").setTabCompleter(new CumulativeTabCompleter(databaseService));

        // 注册API服务
        ServicesManager servicesManager = getServer().getServicesManager();
        servicesManager.register(DepositCumulativeAPI.class, databaseService, this, ServicePriority.Normal);

        // 注册事件监听器
        getServer().getPluginManager().registerEvents(
                new PointsListener(databaseService), this
        );

        // 初始化GUI监听器
        guiListener = new GUIListener(databaseService);
        getServer().getPluginManager().registerEvents(guiListener, this);

        // 打印启动横幅
        Logger.printBanner();
        Logger.info("插件已启用");
    }

    @Override
    public void onDisable() {
        // 关闭数据库连接
        new DatabaseService(this).close();
        Logger.info("插件已禁用");
    }

    public GUIListener getGuiListener() {
        return guiListener;
    }
}